package com.sooth.system.role.service;

import cn.hutool.core.collection.CollUtil;
import com.dream.template.mapper.TemplateMapper;
import com.sooth.system.role.mapper.SysRoleDeptMapper;
import com.sooth.system.role.table.SysRoleDept;
import com.sooth.system.role.view.SysRoleDeptDto;
import com.sooth.system.role.view.SysRoleDeptVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
public class SysRoleDeptServiceImpl implements ISysRoleDeptService {
    private final TemplateMapper templateMapper;
    private final SysRoleDeptMapper roleDeptMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysRoleDeptVo roleDeptVo) {
        Long roleId = roleDeptVo.getRoleId();
        roleDeptMapper.deleteByRoleId(roleId);
        List<Long> deptIds = roleDeptVo.getDeptIds();
        if (CollUtil.isNotEmpty(deptIds)) {
            List<SysRoleDept> roleDepts = new ArrayList<>(deptIds.size());
            for (Long deptId : deptIds) {
                roleDepts.add(new SysRoleDept(roleId, deptId));
            }
            templateMapper.batchInsert(roleDepts);
        }
    }

    @Override
    public List<SysRoleDept> list(SysRoleDeptDto roleDept) {
        return templateMapper.selectList(SysRoleDept.class, roleDept);
    }
}
